﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SharpSoft.WPF.Controls
{
    /// <summary>
    /// 视频播放器 
    /// </summary>
    public class VideoPlayer : Control
    {
        static VideoPlayer()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(VideoPlayer), new FrameworkPropertyMetadata(typeof(VideoPlayer)));
        }
        public VideoPlayer()
        { 
            this.Loaded += VideoPlayer_Loaded;
            this.Unloaded += VideoPlayer_Unloaded;
        }

        private void VideoPlayer_Unloaded(object sender, RoutedEventArgs e)
        {
            this.media?.Stop();
            this.media?.Close();
        }

        private void VideoPlayer_Loaded(object sender, RoutedEventArgs e)
        {
            this.media?.Play();
        }

        private MediaElement media;
        private Border stopStatePanel;
        private Button btn_play;
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.media = (MediaElement)this.GetTemplateChild("media");
            this.stopStatePanel = (Border)this.GetTemplateChild("stopStatePanel");
            this.btn_play = (Button)this.GetTemplateChild("btn_play");
            this.btn_play.Click += Btn_play_Click;
            this.media.MediaOpened += Media_MediaOpened;
            this.media.MediaEnded += Media_MediaEnded;
            this.media.SourceUpdated += Media_SourceUpdated;
            this.media.ScriptCommand += Media_ScriptCommand;
        }

        private void Clock_CurrentStateInvalidated(object sender, EventArgs e)
        {

        }

        private void Clock_CurrentTimeInvalidated(object sender, EventArgs e)
        {

        }

        private void Media_ScriptCommand(object sender, MediaScriptCommandRoutedEventArgs e)
        { 
        }

        private void Media_SourceUpdated(object sender, DataTransferEventArgs e)
        {

        }

        private void Btn_play_Click(object sender, RoutedEventArgs e)
        {
            this.Play();
        }

        private void Media_MediaEnded(object sender, RoutedEventArgs e)
        {
            if (AutoReplay)
            {
                media.Position = TimeSpan.Zero;
                this.Play();
            }
            else
            {
                media?.Stop();//重置时间线
                this.OnStop();
            }

        }

        private void Media_MediaOpened(object sender, RoutedEventArgs e)
        { 
            if (!this.AutoPlay)
            {//媒体打开后如果没指定自动播放则停止播放
                this.Stop();
            }
            else
            {
                this.Play();
            }
        }

        #region 属性

        /// <summary>
        /// 在视频未播放时是否显示操作面板
        /// </summary>
        public bool ShowPanelWhenNotPlaying
        {
            get { return (bool)GetValue(ShowPanelWhenNotPlayingProperty); }
            set { SetValue(ShowPanelWhenNotPlayingProperty, value); }
        }

        public static readonly DependencyProperty ShowPanelWhenNotPlayingProperty =
            DependencyProperty.Register("ShowPanelWhenNotPlaying", typeof(bool), typeof(VideoPlayer), new PropertyMetadata(true));



        /// <summary>
        /// 媒体源
        /// </summary>
        public Uri Source
        {
            get { return (Uri)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(Uri), typeof(VideoPlayer), new PropertyMetadata(null));


        /// <summary>
        /// 控制视频的音量（取值范围从0到1,默认为1）
        /// </summary>
        public double Volume
        {
            get { return (double)GetValue(VolumeProperty); }
            set { SetValue(VolumeProperty, value); }
        }

        public static readonly DependencyProperty VolumeProperty =
            DependencyProperty.Register("Volume", typeof(double), typeof(VideoPlayer), new PropertyMetadata(1d));


        /// <summary>
        /// 左右声道音量平衡(取值范围为-1到1，默认为0)
        /// </summary>
        public double Balance
        {
            get { return (double)GetValue(BalanceProperty); }
            set { SetValue(BalanceProperty, value); }
        }

        public static readonly DependencyProperty BalanceProperty =
            DependencyProperty.Register("Balance", typeof(double), typeof(VideoPlayer), new PropertyMetadata(0d));


        /// <summary>
        /// 是否静音
        /// </summary> 
        public bool IsMuted
        {
            get { return (bool)GetValue(IsMutedProperty); }
            set { SetValue(IsMutedProperty, value); }
        }

        public static readonly DependencyProperty IsMutedProperty =
            DependencyProperty.Register("IsMuted", typeof(bool), typeof(VideoPlayer), new PropertyMetadata(false));



        /// <summary>
        /// 当前状态
        /// </summary>
        public VideoPlayerStatus Status
        {
            get { return (VideoPlayerStatus)GetValue(StatusProperty); }
            private set { SetValue(StatusProperty, value); }
        }

        public static readonly DependencyProperty StatusProperty =
            DependencyProperty.Register("Status", typeof(VideoPlayerStatus), typeof(VideoPlayer), new PropertyMetadata(VideoPlayerStatus.None));




        /// <summary>
        /// 定义视频的拉伸方式
        /// </summary>
        public Stretch Stretch
        {
            get { return (Stretch)GetValue(StretchProperty); }
            set { SetValue(StretchProperty, value); }
        }

        public static readonly DependencyProperty StretchProperty =
            DependencyProperty.Register("Stretch", typeof(Stretch), typeof(VideoPlayer), new PropertyMetadata(Stretch.Uniform));

        /// <summary>
        /// 公开内部使用的<see cref="MediaElement"/>,请不要直接对它进行控制，这会丢失当前视频的状态监控。
        /// </summary>
        public MediaElement MediaElement
        {
            get
            {
                return media;
            }
        }

        /// <summary>
        /// 获取视频的持续时间
        /// </summary>
        public Duration NaturalDuration
        {
            get
            {
                if (media == null)
                {
                    throw new Exception("视频尚未加载，无法获取持续时间。");
                }
                return media.NaturalDuration;
            }
        }

        /// <summary>
        /// 媒体加载后是否自动开始播放
        /// </summary>
        public bool AutoPlay
        {
            get { return (bool)GetValue(AutoPlayProperty); }
            set { SetValue(AutoPlayProperty, value); }
        }

        public static readonly DependencyProperty AutoPlayProperty =
            DependencyProperty.Register("AutoPlay", typeof(bool), typeof(VideoPlayer), new PropertyMetadata(false));


        /// <summary>
        /// 视频播放完毕后是否自动重新播放
        /// </summary>
        public bool AutoReplay
        {
            get { return (bool)GetValue(AutoReplayProperty); }
            set { SetValue(AutoReplayProperty, value); }
        }

        public static readonly DependencyProperty AutoReplayProperty =
            DependencyProperty.Register("AutoReplay", typeof(bool), typeof(VideoPlayer), new PropertyMetadata(false));



        /// <summary>
        /// 指定视频停止播放时视频停留在的时间点
        /// </summary>
        public TimeSpan? StayWhenStop
        {
            get { return (TimeSpan?)GetValue(StayWhenStopProperty); }
            set { SetValue(StayWhenStopProperty, value); }
        }

        public static readonly DependencyProperty StayWhenStopProperty =
            DependencyProperty.Register("StayWhenStop", typeof(TimeSpan?), typeof(VideoPlayer), new PropertyMetadata(null));


        #endregion


        public void Play()
        {
            if (this.Status == VideoPlayerStatus.Stoped)
            {//从停止状态开始播放重置时间线
                media?.Stop();
            }
            media?.Play();
            this.OnPlay();
            var v = media.Volume;
            media.Volume = 1 - v;
            media.Volume = v;
        }

        public void Pause()
        {
            if (media != null && media.CanPause)
            {
                media?.Pause();
                this.OnPause();
            }

        }

        public void Stop()
        {
            media?.Stop();
            this.OnStop();
        }

        public void Close()
        {
            media?.Close();
            this.OnClosed();

        }

        /// <summary>
        /// 在媒体播放完成或手动停止后触发
        /// </summary>
        protected virtual void OnStop()
        {
            this.Status = VideoPlayerStatus.Stoped;
            if (this.StayWhenStop.HasValue)
            {
                if (this.media != null && this.media.HasVideo)
                {//有视频内容才停止到指定的时间
                    this.media.Pause();
                    this.media.Position = StayWhenStop.Value;
                }
            }
            if (this.stopStatePanel != null && ShowPanelWhenNotPlaying)
            {
                this.stopStatePanel.Visibility = Visibility.Visible;
            }
        }

        protected virtual void OnPause()
        {
            this.Status = VideoPlayerStatus.Paused;
            if (this.stopStatePanel != null && ShowPanelWhenNotPlaying)
            {
                this.stopStatePanel.Visibility = Visibility.Visible;
            }
        }

        protected void OnPlay()
        {
            this.Status = VideoPlayerStatus.Playing;
            if (this.stopStatePanel != null)
            {
                this.stopStatePanel.Visibility = Visibility.Hidden;
            }
        }

        protected void OnClosed()
        {
            this.Status = VideoPlayerStatus.None;

        }

        protected virtual void OnStatusChanged()
        {
            this.StatusChanged?.Invoke(this, EventArgs.Empty);
        }
        public event EventHandler StatusChanged;
        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
            if (e.Property == SourceProperty)
            {
                if (this.Source == null)
                {
                    this.Close();
                }
            }
            else if (e.Property == StatusProperty)
            {
                this.OnStatusChanged();
            }
        }
    }
    /// <summary>
    /// 视频播放状态
    /// </summary>
    public enum VideoPlayerStatus
    {
        None,
        Playing,
        Paused,
        Stoped
    }
}
